<!--
 * @Description: 单品赠送功能
 * @Author: duan_shuangjun 丶
 * @Date: 2025-09-10 16:30:30
-->
<template>
  <custom-dialog v-model:visible="dialogVisible" curent-class="gift-food-dialog">
    <!-- 菜品赠送 -->
    <div
      class="dialog-content"
      v-if="selectedFood && selectedFood.is_present !== 1 && selectedFood.is_present !== 2"
    >
      <div class="title">赠送</div>
      <div class="description">
        <div class="name">{{ selectedFood.name }}</div>
        <div class="count">共{{ selectedFood.num }}份</div>
      </div>
      <div class="scroll-content">
        <div class="title">赠送原因</div>
        <div class="scroll-list">
          <div
            class="scroll-item"
            :class="{ 'scroll-item-active': selectActiveIndex === index }"
            v-for="(item, index) in reasonList"
            :key="item.name + index"
            @click="handleSelectReason(index, item.name)"
          >
            {{ item.name }}
          </div>
        </div>
      </div>
      <div class="form-box">
        <div class="form-item">
          <div class="desc">赠送原因</div>
          <div class="dialog-input">
            <input
              class="input"
              v-model.trim="reasonKeyword"
              type="text"
              placeholder="请在上方选择或输入赠送原因"
            />
            <img
              class="image"
              src="@/assets/images/home/input-clear.png"
              alt=""
              @click="handleClearInput(1)"
              v-if="reasonKeyword"
            />
          </div>
        </div>
        <div class="form-item">
          <div class="desc">赠送数量</div>
          <div class="dialog-input">
            <input
              class="input"
              v-model.trim="countKeyword"
              type="text"
              @input="handleInputCount"
              placeholder="请输入赠送数量"
            />
            <img
              class="image"
              src="@/assets/images/home/input-clear.png"
              alt=""
              @click="handleClearInput(2)"
              v-if="countKeyword"
            />
          </div>
        </div>
      </div>
      <div class="btn-box">
        <el-button class="cancel-btn" @click="dialogVisible = false">取消</el-button>
        <el-button class="confirm-btn" @click="handleConfirm" :loading="loading">
          {{ loading ? '处理中...' : '确定赠送' }}
        </el-button>
      </div>
    </div>

    <!-- 菜品撤销赠送 -->
    <div
      class="dialog-content"
      v-if="selectedFood && (selectedFood.is_present === 1 || selectedFood.is_present === 2)"
    >
      <div class="title">撤销赠送</div>
      <div class="description">
        <div class="name">{{ selectedFood.name }}</div>
        <div class="count">共{{ selectedFood.num }}份</div>
      </div>

      <div class="form-box">
        <div class="form-item">
          <div class="desc" style="margin-right: 10px">撤赠数量</div>
          <div class="dialog-input">
            <input
              class="input"
              v-model.trim="countKeyword"
              type="text"
              @input="handleInputCount"
              placeholder="请输入撤赠数量"
            />
            <img
              class="image"
              src="@/assets/images/home/input-clear.png"
              alt=""
              @click="handleClearInput(2)"
              v-if="countKeyword"
            />
          </div>
        </div>
      </div>
      <div class="btn-box">
        <el-button class="cancel-btn" @click="dialogVisible = false">取消</el-button>
        <el-button class="confirm-btn" @click="handleConfirmRevoke" :loading="loading">
          {{ loading ? '处理中...' : '确定撤赠' }}
        </el-button>
      </div>
    </div>
  </custom-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { orderFoodPresent, orderFoodUnpresent, foodReasonList } from '@/api/food'
import CustomDialog from '@/components/CustomDialog/Index.vue'
import { ElButton } from 'element-plus'

interface Props {
  deskDetail: any
  selectFoodActiveIndex: number
  modelValue: boolean
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'refreshData'): void
  (e: 'refreshDesk'): void
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  deskDetail: () => ({}),
  selectFoodActiveIndex: -1
})

const emit = defineEmits<Emits>()

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.modelValue,
  set: val => emit('update:modelValue', val)
})

// 选中的菜品
const selectedFood = ref<any>(null)
// 加载状态
const loading = ref(false)
// 列表加载状态
const listLoading = ref(false)
// 赠送原因关键词
const reasonKeyword = ref('')
// 赠送数量关键词
const countKeyword = ref('')
// 赠送原因列表
const reasonList = ref<{ name: string }[]>([])
// 选中对应原因的索引
const selectActiveIndex = ref(-1)

// 获取菜品赠送的原因列表
const getFoodReasonList = async () => {
  listLoading.value = true
  try {
    const res = await foodReasonList({ type: 20 })
    if (res.status === 200) {
      const dataList: { name: string }[] = []
      res.data.forEach((item: string) => {
        dataList.push({ name: item })
      })
      reasonList.value = dataList
    }
  } catch (error) {
    console.error('获取赠送原因列表失败:', error)
  } finally {
    listLoading.value = false
  }
}

// 清空输入框
const handleClearInput = (num: number) => {
  if (num === 1) {
    reasonKeyword.value = ''
    selectActiveIndex.value = -1
  } else {
    countKeyword.value = ''
  }
}

// 选中对应的原因
const handleSelectReason = (index: number, name: string) => {
  selectActiveIndex.value = index
  reasonKeyword.value = name
}

// 处理数量输入，只允许输入数字并限制最大值
const handleInputCount = (event: Event) => {
  const target = event.target as HTMLInputElement
  // 只允许输入数字
  let value = target.value.replace(/[^\d]/g, '')

  // 如果输入的值不为空
  if (value) {
    // 转换为数字
    const numValue = parseInt(value)
    // 如果输入的数字大于菜品总数量，则限制为菜品总数量
    if (selectedFood.value && numValue > selectedFood.value.num) {
      value = selectedFood.value.num.toString()
    }
  }

  countKeyword.value = value
}

// 重置数据
const resetData = () => {
  selectActiveIndex.value = -1
  reasonKeyword.value = ''
  countKeyword.value = ''
}

// 监听对话框打开状态
watch(
  () => dialogVisible.value,
  val => {
    if (val) {
      // 获取菜品赠送的原因列表
      getFoodReasonList()
      // 获取选中的菜品信息
      selectedFood.value = props.deskDetail.foodList?.[props.selectFoodActiveIndex]
      // 重置数据
      resetData()
      // 默认设置为全部份数
      if (selectedFood.value) {
        countKeyword.value = selectedFood.value.num.toString()
      }
    }
  }
)

// 确认赠送处理
const handleConfirm = async () => {
  if (!reasonKeyword.value) {
    ElMessage.warning('赠送原因不能为空')
    return
  }

  if (!countKeyword.value) {
    ElMessage.warning('赠送数量不能为空')
    return
  }

  if (parseInt(countKeyword.value) <= 0) {
    ElMessage.warning('赠送数量不能小于或等于0')
    return
  }

  if (parseInt(countKeyword.value) > selectedFood.value.num) {
    ElMessage.warning('赠送数量不能大于当前菜品的数量')
    return
  }

  if (loading.value) return

  try {
    loading.value = true

    const params = {
      id: selectedFood.value.id,
      num: parseInt(countKeyword.value),
      reason: reasonKeyword.value
    }

    const res = await orderFoodPresent(params)
    if (res.status === 200) {
      ElMessage.success(res.data?.message || '赠送成功')
      dialogVisible.value = false
      emit('refreshData')
      emit('refreshDesk')
    } else {
      ElMessage.error(res.data?.message || '赠送失败')
    }
  } catch (error) {
    console.error('赠送失败:', error)
    ElMessage.error('赠送失败')
  } finally {
    loading.value = false
  }
}

// 确认撤销赠送处理
const handleConfirmRevoke = async () => {
  if (!countKeyword.value) {
    ElMessage.warning('撤赠数量不能为空')
    return
  }

  if (parseInt(countKeyword.value) <= 0) {
    ElMessage.warning('撤赠数量不能小于或等于0')
    return
  }

  if (parseInt(countKeyword.value) > selectedFood.value.num) {
    ElMessage.warning('撤赠数量不能大于当前菜品的数量')
    return
  }

  if (loading.value) return

  try {
    loading.value = true

    const params = {
      id: selectedFood.value.id,
      num: parseInt(countKeyword.value)
    }

    const res = await orderFoodUnpresent(params)
    if (res.status === 200) {
      ElMessage.success(res.data?.message || '撤销赠送成功')
      dialogVisible.value = false
      emit('refreshData')
      emit('refreshDesk')
    } else {
      ElMessage.error(res.data?.message || '撤销赠送失败')
    }
  } catch (error) {
    console.error('撤销赠送失败:', error)
    ElMessage.error('撤销赠送失败')
  } finally {
    loading.value = false
  }
}
</script>

<style lang="scss" scoped>
.dialog-content {
  .title {
    font-size: 20px;
    font-family:
      PingFang SC,
      PingFang SC-Bold;
    font-weight: 700;
    text-align: center;
    color: #353535;
  }

  .description {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 16px;
    font-size: 16px;
    font-family:
      PingFang SC,
      PingFang SC-Regular;
    font-weight: 400;
    text-align: center;
    color: #353535;

    .count {
      margin-left: 16px;
    }
  }

  .position-bgc {
    position: absolute;
    left: 0;
    top: 90px;
    z-index: 1;
    width: 100%;
    height: 197px;
    background: #f4f4f4;
  }

  .scroll-content {
    background: #f4f4f4;
    height: 197px;
    box-sizing: border-box;
    padding: 20px 0;
    overflow-y: auto;
    margin-top: 20px;

    .title {
      position: relative;
      z-index: 2;
      font-size: 16px;
      font-family:
        PingFang SC,
        PingFang SC-Regular;
      font-weight: 400;
      text-align: left;
      color: #333333;
      padding: 0px 40px;
    }

    .scroll-list {
      width: 516px;
      position: relative;
      z-index: 2;
      padding: 0px 40px;
      display: flex;
      align-items: center;
      gap: 20px;
      flex-wrap: wrap;

      .scroll-item {
        min-width: 120px;
        height: 48px;
        line-height: 48px;
        background: #ffffff;
        border: 1px solid #d2d2d2;
        border-radius: 12px;
        font-size: 14px;
        font-family:
          PingFang SC,
          PingFang SC-Regular;
        font-weight: 400;
        text-align: center;
        color: #333333;
        margin-top: 20px;
        cursor: pointer;
      }

      .scroll-item-active {
        border-color: #7c0a03 !important;
        color: #7c0a03 !important;
      }
    }
  }

  //滚动条整体的大小
  .scroll-content::-webkit-scrollbar {
    width: 6px;
    height: 0;
  }

  //滚动条里滑动的滑块
  .scroll-content::-webkit-scrollbar-thumb {
    height: 90px;
    background: #d2d2d2;
    border-radius: 3px;
  }

  //滚动条底层样式
  .scroll-content::-webkit-scrollbar-track {
    display: none;
  }

  .form-box {
    padding: 30px 40px;

    .form-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-top: 20px;

      .desc {
        font-size: 16px;
        font-family:
          PingFang SC,
          PingFang SC-Regular;
        font-weight: 400;
        color: #333333;
      }

      .dialog-input {
        width: 420px;
        height: 48px;
        background: #ffffff;
        border: 1px solid #d2d2d2;
        border-radius: 12px;
        box-sizing: border-box;
        padding: 0 20px;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .input {
          width: 400px;
          font-size: 14px;
          font-family:
            PingFang SC,
            PingFang SC-Regular;
          font-weight: 400;
          text-align: left;
          color: #333333;
          outline: none;
          border: none;
        }

        .image {
          flex-shrink: 0;
          width: 24px;
          height: 24px;
          cursor: pointer;
        }
      }
    }
  }

  .btn-box {
    padding: 50px 38px 0 38px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .cancel-btn {
      width: 190px;
      height: 52px;
      border: 1px solid #d2d2d2;
      border-radius: 12px;
      font-size: 18px;
      font-family:
        PingFang SC,
        PingFang SC-Regular;
      font-weight: 400;
      text-align: center;
      color: #353535;
      line-height: 52px;
      cursor: pointer;
    }

    .confirm-btn {
      width: 190px;
      height: 52px;
      background: #7c0a03;
      border-radius: 12px;
      font-size: 18px;
      font-family:
        PingFang SC,
        PingFang SC-Regular;
      font-weight: 400;
      text-align: center;
      color: #ffffff;
      line-height: 52px;
      cursor: pointer;

      &.loading {
        opacity: 0.7;
        cursor: not-allowed;
      }
    }
  }
}
</style>
<style>
.gift-food-dialog {
  padding: 50px 0px !important;
}
</style>
